package com.nananren.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nananren.common.Result;
import com.nananren.domain.Employee;
import com.nananren.domain.ExceptionLog;
import com.nananren.domain.OperateLog;
import com.nananren.dto.ExceptionLogDto;
import com.nananren.service.EmployeeService;
import com.nananren.service.ExceptionLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/exceptionLog")
@Slf4j
public class ExceptionLogController {

    @Autowired
    private ExceptionLogService exceptionLogService;
    @Autowired
    private EmployeeService employeeService;

    // 条件分页查询
    @GetMapping("/page")
    public Result page(int page, int pageSize, String exceptionUser, String exceptionType, String exceptionMethod,
                       String exceptionClass, String exceptionArgs, String exceptionDescription,
                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")LocalDateTime begin,
                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")LocalDateTime end) {
        log.info("分页查询条件：page: {}, pageSize: {}, exceptionUser: {}, exceptionType: {}, exceptionMethod: {}," +
                "exceptionClass: {}, exceptionArgs: {}, exceptionDescription: {}, begin: {}, end: {}",
                page, pageSize, exceptionUser, exceptionType, exceptionMethod, exceptionClass, exceptionArgs,
                exceptionDescription, begin, end);
        Page<ExceptionLog> exceptionLogPage = new Page<>(page, pageSize);
        Page<ExceptionLogDto> exceptionLogDtoPage = new Page<>();
        // 条件构造器
        LambdaQueryWrapper<ExceptionLog> exceptionLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 异常人exceptionUser
        if (exceptionUser != null) {
            LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            employeeLambdaQueryWrapper.like(Employee::getUsername, exceptionUser);
            List<Employee> list = employeeService.list(employeeLambdaQueryWrapper);
            if (list.size() == 0) {
                return Result.error("暂无数据");
            }
            // 有数据
            List<Long> ids = list.stream().map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            exceptionLogLambdaQueryWrapper.in(ExceptionLog::getOperateExceptionUserId, ids);
        }

        // 异常类型exceptionType
        exceptionLogLambdaQueryWrapper.like(exceptionType != null, ExceptionLog::getExceptionType, exceptionType);
        // 异常方法exceptionMethod
        exceptionLogLambdaQueryWrapper.like(exceptionMethod != null, ExceptionLog::getExceptionMethod, exceptionMethod);
        // 异常类exceptionClass
        exceptionLogLambdaQueryWrapper.like(exceptionClass != null, ExceptionLog::getExceptionClass, exceptionClass);
        // 异常参数exceptionArgs
        exceptionLogLambdaQueryWrapper.like(exceptionArgs != null, ExceptionLog::getExceptionArgs, exceptionArgs);
        // 异常描述
        exceptionLogLambdaQueryWrapper.like(exceptionDescription != null,
                ExceptionLog::getExceptionDescription, exceptionDescription);
        // 日期条件
        // begin等于null，end不等于null，查询borrow_time小于等于end的所有数据
        exceptionLogLambdaQueryWrapper.le(begin == null && end != null, ExceptionLog::getExceptionCreateTime, end);
        // begin不等于null，end等于null，查询borrow_time大于等于begin的所有数据
        exceptionLogLambdaQueryWrapper.ge(begin != null && end == null, ExceptionLog::getExceptionCreateTime, begin);
        // begin和end都不等于null，查询borrow_time大于等于begin并小于等于end的所有数据
        exceptionLogLambdaQueryWrapper.between(begin != null && end != null, ExceptionLog::getExceptionCreateTime, begin, end);
        // 根据操作时间倒序排序
        exceptionLogLambdaQueryWrapper.orderByDesc(ExceptionLog::getExceptionCreateTime);
        // 分页查询
        exceptionLogService.page(exceptionLogPage, exceptionLogLambdaQueryWrapper);

        // 对象拷贝
        BeanUtils.copyProperties(exceptionLogPage, exceptionLogDtoPage, "records");
        List<ExceptionLog> records = exceptionLogPage.getRecords();
        List<ExceptionLogDto> result = records.stream().map(item -> {
            ExceptionLogDto exceptionLogDto = new ExceptionLogDto();
            // 对象拷贝
            BeanUtils.copyProperties(item, exceptionLogDto);
            Employee emp = employeeService.getById(item.getOperateExceptionUserId());
            if (emp != null) {
                exceptionLogDto.setOperateUser(emp.getUsername());
            }
            return exceptionLogDto;
        }).collect(Collectors.toList());

        // 给exceptionLogDtoPage的recordes赋值
        exceptionLogDtoPage.setRecords(result);

        return exceptionLogDtoPage.getTotal() != 0 ? Result.success(exceptionLogDtoPage) : Result.error("暂无数据");
    }

    // 根据id查询异常日志
    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id) {
        log.info("根据id查询异常数据：{}", id);

        // 根据id获得异常信息
        ExceptionLog exceptionLog = exceptionLogService.getById(id);
        if (exceptionLog == null) {
            return Result.error("暂无数据");
        }
        ExceptionLogDto exceptionLogDto = new ExceptionLogDto();
        // 对象拷贝
        BeanUtils.copyProperties(exceptionLog, exceptionLogDto);
        // 根据查询出来的异常对象中的操作人id获得操作人姓名
        Employee emp = employeeService.getById(exceptionLog.getOperateExceptionUserId());
        if (emp == null) {
            return Result.error("数据异常，请联系管理员");
        }
        exceptionLogDto.setOperateUser(emp.getUsername());

        return Result.success(exceptionLogDto);

    }

    // 根据id删除异常日志
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Long id) {
        log.info("根据id删除日志，id为：{}", id);
        exceptionLogService.removeById(id);
        return Result.success("删除成功");
    }
}
